package top.byteio.common.message.messager;

import com.aliyun.dysmsapi20180501.Client;
import com.aliyun.dysmsapi20180501.models.BatchSendMessageToGlobeResponse;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import top.byteio.common.message.client.MessagerHelper;
import top.byteio.common.message.client.SMSAliyunMessageHelper;
import top.byteio.common.message.pojo.MessagerProperty;
import top.byteio.common.message.pojo.Notice;

@Slf4j
@Setter
public class SmsAliyunMessager implements NoticeMessager {

    private static volatile SmsAliyunMessager instance;

    private final MessagerProperty property;

    public SmsAliyunMessager(MessagerProperty property) {
        this.property = property;
    }

    public static SmsAliyunMessager getInstance(MessagerProperty property) {
        if (instance == null) {
            synchronized (SmsAliyunMessager.class) {
                if (instance == null) {
                    instance = new SmsAliyunMessager(property);
                }
            }
        }
        return instance;
    }

    @Override
    public boolean send(Notice notice) {
        Client client = helper().getHelper(property);
        try {
            com.aliyun.dysmsapi20180501.models.BatchSendMessageToGlobeRequest request = new com.aliyun.dysmsapi20180501.models.BatchSendMessageToGlobeRequest()
                    .setTo(notice.getTo())
                    .setFrom(notice.getFrom())
                    .setMessage(notice.getContent());
            BatchSendMessageToGlobeResponse response = client.batchSendMessageToGlobe(request);
            String code = response.getBody().responseCode;
            if (!"OK".equals(code)) {
                log.error("阿里云短信发送失败: {}", response);
                return false;
            }
            log.info("阿里云短信发送成功: {}", response);
            return true;
        } catch (Exception e) {
            log.error("阿里云短信发送失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public MessagerHelper<Client> helper() {
        return new SMSAliyunMessageHelper();
    }
}
